package com.ls.controller;

import com.ls.entity.DiscussPost;
import com.ls.entity.Page;
import com.ls.entity.User;
import com.ls.entity.vo.DiscussPostVo;
import com.ls.service.ElasticsearchService;
import com.ls.service.LikeService;
import com.ls.service.UserService;
import com.ls.util.CommunityConstant;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ls
 * @version v1.0
 * @description 搜索
 * @date 2021/8/21 20:18
 */
@Controller
public class SearchController {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @GetMapping("/search")
    public String search(String keyword, Page page, Model model) {
        // 搜索帖子
        org.springframework.data.domain.Page<DiscussPost> searchResult = elasticsearchService.pageSearchDiscussPost(keyword, page.getCurrentPage() - 1, page.getPageSize());
        if (searchResult == null) {
            model.addAttribute("msg", "未找到与 <em>" + keyword + "</em> 相关的内容! ");
            model.addAttribute("keyword", keyword);
            page.setPath("/search?keyword=" + keyword);
            page.setTotalCount(0);
            return "site/search";
        }
        // 聚合数据
        List<DiscussPostVo> discussPostVos = searchResult.stream()
                .map(discussPost -> {
                    DiscussPostVo discussPostVo = new DiscussPostVo();
                    BeanUtils.copyProperties(discussPost, discussPostVo);
                    User postUser = userService.queryUserById(discussPost.getUserId());
                    discussPostVo.setUser(postUser);
                    long postLikeCount = likeService.getEntityLikeCount(CommunityConstant.ENTITY_TYPE_POST, discussPost.getId());
                    discussPostVo.setLikeCount(postLikeCount);
                    return discussPostVo;
                }).collect(Collectors.toList());
        model.addAttribute("discussPostVos", discussPostVos);
        model.addAttribute("keyword", keyword);
        // 设置分页信息
        page.setPath("/search?keyword=" + keyword);
        page.setTotalCount((int) searchResult.getTotalElements());

        return "site/search";
    }

}
